package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.common.ThreadLocal;
import com.reggie.pojo.Employee;
import com.reggie.service.impl.EmployeeServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/employee")
@Transactional
public class EmployeeController {
    @Autowired
    EmployeeServiceImpl service;

    //登录操作
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        //先看看这个用户存不存在
        boolean flag_exits = service.selectByUsername(employee.getUsername());
        if (flag_exits) {
            //这个用户存在的话看看他的Status是什么如果是0则未启用
            //这个用户是存在的，执行登录操作
            //在登录之前先对这个对象的密码进行加密
            employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
            Employee login_employee = service.login(employee);
            if (login_employee != null) {
                if (login_employee.getStatus() == 0) {
                    return R.error("这个用户未启用！");
                }
                //把查询到的用户存储到Session中
                request.getSession().setAttribute("employee", login_employee.getId());
                return R.success(login_employee);
            } else {
                return R.error("用户名或密码错误！");
            }
        } else {
            return R.error("登录失败！用户不存在！");
        }
    }

    //添加员工操作
    @PostMapping("/add")
    public R<Employee> addEmployee(@RequestBody Employee employee) throws IOException {
        System.out.println("来到增加员工的服务器中");
        System.out.println(employee);
//        //获取一个注册的日期
//        LocalDateTime now = LocalDateTime.now();
        //生成一个随机的密码
        Random r = new Random();
        String password = Integer.toString(r.nextInt(10000000, 99999999));
        FileOutputStream fos = new FileOutputStream(new File("src/main/java/com/reggie/text/user_password.txt"), true);
        fos.write(employee.getUsername().getBytes());
        fos.write(" : ".getBytes());
        fos.write(password.getBytes());
        fos.write("\n".getBytes());
        fos.close();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        employee.setPassword(password);
        employee.setStatus(1);
        //设置这里的创建日期和更新日期统一放在通用字段填充中，不在添加操作中进行下一步赋值
//        employee.setCreateTime(now);
//        employee.setUpdateTime(now);
//        Long emp_Id = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(emp_Id);
//        employee.setUpdateUser(emp_Id);
        boolean flag = service.addEmployee(employee);
        if (flag) {
            return R.success(null);
        } else {
            return R.error("添加失败");
        }
    }

    //分页查询操作
    @GetMapping("/page")
    public R<Page<Employee>> pageList(Integer page, Integer pageSize, String name) {
        System.out.println("分页查询");
        System.out.println(page + ":" + pageSize + ":" + name);
        //分页查询过滤器
        Page page_now = new Page(page, pageSize);
        //添加模糊查询
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //指定一个排序规则
//        lqw.orderByDesc(Employee::getUpdateTime);
        //在这里返回的数据设置为page对象即可，在mp查询完成后会将数据封装在page对象中
        service.selectByPage(page_now, lqw);
        return R.success(page_now);
    }

    //退出登录操作
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功！");
    }


    //修改员工状态
    @PutMapping
    public R<Boolean> updateStatus(@RequestBody Employee employee) {
        System.out.println("修改状态！");
        //获取到这个要修改状态的对象，修改他的状态为1
        System.out.println(employee);
        Employee emp_now = service.SelectById(employee.getId());
        emp_now.setStatus(employee.getStatus());
        boolean b = service.upDataStatus(emp_now);
        if (b) {
            return R.success(b);
        }
        return R.error("未知错误！");
    }

    //按照id进行查询
    @GetMapping(value = "/{id}")
    public R<Employee> selectById(@PathVariable Long id) {
        System.out.println(id);
        //将要进行修改的对象的id存储到session中
        return R.success(service.selectById(id));
    }

    //修改员工服务器
    @PutMapping("/add")
    public R<String> updateEmployee(@RequestBody Employee employee) {
        System.out.println("修改员工服务器");
        System.out.println(employee);
        service.updateEmployee(employee);
        return R.success("修改成功");
    }
}
